from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class CustomUserManager(BaseUserManager):
    def create_user(self, username, email, password=None):
        if not username:
            raise ValueError('Users must have a username')
        if not email:
            raise ValueError('Users must have an email address')

        # 直接明文存储
        user = self.model(
            username=username,
            email=self.normalize_email(email),
            password=password  # 明文赋值
        )
        user.save(using=self._db)
        return user


class User(AbstractBaseUser):
    username = models.CharField(max_length=150, unique=True)
    email = models.EmailField()
    created_at = models.DateTimeField(auto_now_add=True)

    # 必须添加的字段（最小化）
    is_active = models.BooleanField(default=True)

    objects = BaseUserManager()  # 使用原生管理器

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    # 关键：覆盖密码处理方法
    def set_password(self, raw_password):
        """直接存储明文"""
        self.password = raw_password

    def check_password(self, raw_password):
        """直接比较明文"""
        return self.password == raw_password

    class Meta:
        db_table = 'auth_user'